from django.core.management.base import BaseCommand
from django.utils import timezone
from myapp.models import (
    Platform, Keyword, SentimentData, SentimentKeywordRelation,
    MonitorTarget, AlertRule, AlertLog, SystemStatus, DailyStatistics
)
import random
from datetime import timedelta, datetime

class Command(BaseCommand):
    help = '添加示例数据用于测试和演示'

    def handle(self, *args, **kwargs):
        self.stdout.write('开始添加示例数据...')
        
        # 添加平台数据
        platforms = self.add_platforms()
        
        # 添加关键词数据
        keywords = self.add_keywords()
        
        # 添加监控目标数据
        targets = self.add_monitor_targets(keywords)
        
        # 添加舆情数据和关联关键词
        sentiments = self.add_sentiment_data(platforms, keywords)
        
        # 添加预警规则
        rules = self.add_alert_rules(targets)
        
        # 添加预警日志
        self.add_alert_logs(rules, sentiments)
        
        # 添加系统状态
        self.add_system_status()
        
        # 添加每日统计
        self.add_daily_statistics()
        
        self.stdout.write(self.style.SUCCESS('示例数据添加完成!'))

    def add_platforms(self):
        """添加平台数据"""
        platforms = [
            {"name": "微博", "icon": "weibo"},
            {"name": "知乎", "icon": "zhihu"},
            {"name": "微信", "icon": "wechat"},
            {"name": "抖音", "icon": "douyin"},
            {"name": "快手", "icon": "kuaishou"},
            {"name": "bilibili", "icon": "bilibili"},
            {"name": "今日头条", "icon": "toutiao"},
            {"name": "小红书", "icon": "xiaohongshu"}
        ]
        
        # 清空现有数据
        Platform.objects.all().delete()
        
        created_platforms = []
        for p in platforms:
            platform = Platform.objects.create(
                name=p["name"],
                icon=p["icon"],
                is_active=True
            )
            created_platforms.append(platform)
        
        self.stdout.write(f'已添加 {len(created_platforms)} 个平台')
        return created_platforms

    def add_keywords(self):
        """添加关键词数据"""
        keywords = [
            {"word": "人工智能", "weight": 95},
            {"word": "数据安全", "weight": 87},
            {"word": "疫情防控", "weight": 82},
            {"word": "数字经济", "weight": 78},
            {"word": "远程办公", "weight": 76},
            {"word": "5G技术", "weight": 75},
            {"word": "元宇宙", "weight": 72},
            {"word": "区块链", "weight": 68},
            {"word": "新能源", "weight": 65},
            {"word": "碳中和", "weight": 63},
            {"word": "教育改革", "weight": 61},
            {"word": "医疗健康", "weight": 60},
            {"word": "电子商务", "weight": 58},
            {"word": "短视频", "weight": 55},
            {"word": "直播带货", "weight": 52},
            {"word": "智能家居", "weight": 50},
            {"word": "物联网", "weight": 48},
            {"word": "大数据", "weight": 45},
            {"word": "云计算", "weight": 43},
            {"word": "芯片技术", "weight": 40}
        ]
        
        # 清空现有数据
        Keyword.objects.all().delete()
        
        created_keywords = []
        for kw in keywords:
            keyword = Keyword.objects.create(
                word=kw["word"],
                weight=kw["weight"]
            )
            created_keywords.append(keyword)
        
        self.stdout.write(f'已添加 {len(created_keywords)} 个关键词')
        return created_keywords

    def add_monitor_targets(self, keywords):
        """添加监控目标数据"""
        targets = [
            {"name": "腾讯公司", "type": 1, "is_priority": True, "description": "腾讯是中国领先的互联网公司"},
            {"name": "阿里巴巴", "type": 1, "is_priority": True, "description": "阿里巴巴是中国领先的电商平台"},
            {"name": "字节跳动", "type": 1, "is_priority": True, "description": "字节跳动是短视频行业的龙头企业"},
            {"name": "马云", "type": 2, "is_priority": False, "description": "阿里巴巴创始人"},
            {"name": "马化腾", "type": 2, "is_priority": False, "description": "腾讯创始人"},
            {"name": "数字人民币", "type": 3, "is_priority": True, "description": "中国央行发行的法定数字货币"},
            {"name": "元宇宙概念", "type": 3, "is_priority": True, "description": "虚拟与现实融合的数字生活空间"},
            {"name": "ChatGPT", "type": 4, "is_priority": True, "description": "OpenAI开发的人工智能聊天机器人"}
        ]
        
        # 清空现有数据
        MonitorTarget.objects.all().delete()
        
        created_targets = []
        for t in targets:
            target = MonitorTarget.objects.create(
                name=t["name"],
                type=t["type"],
                is_priority=t["is_priority"],
                description=t["description"]
            )
            
            # 随机关联3-5个关键词
            num_keywords = random.randint(3, 5)
            selected_keywords = random.sample(keywords, min(num_keywords, len(keywords)))
            for keyword in selected_keywords:
                target.keywords.add(keyword)
            
            created_targets.append(target)
        
        self.stdout.write(f'已添加 {len(created_targets)} 个监控目标')
        return created_targets

    def add_sentiment_data(self, platforms, keywords):
        """添加舆情数据和关联关键词"""
        # 清空现有数据
        SentimentData.objects.all().delete()
        SentimentKeywordRelation.objects.all().delete()
        
        # 生成一些示例舆情标题和内容
        sentiments_data = [
            {
                "title": "人工智能技术在医疗领域的最新应用",
                "content": "近日，多家医院开始应用人工智能技术辅助医生诊断，提高了诊断准确率。专家表示，AI在医疗领域的应用前景广阔。",
                "sentiment_value": 0.8
            },
            {
                "title": "数据安全问题引发广泛关注",
                "content": "随着数字化进程加速，数据安全问题日益突出。多家企业遭遇数据泄露，用户隐私保护问题亟待解决。",
                "sentiment_value": -0.6
            },
            {
                "title": "疫情防控常态化下的经济发展",
                "content": "在疫情防控常态化背景下，各行各业积极寻求转型。线上消费、远程办公等新模式助力经济复苏。",
                "sentiment_value": 0.3
            },
            {
                "title": "数字经济成为国家战略新支点",
                "content": "国家发改委近日发布《数字经济发展规划》，将数字经济上升为国家战略。预计到2025年，数字经济规模将达到GDP的25%。",
                "sentiment_value": 0.7
            },
            {
                "title": "远程办公成为新常态，企业如何应对",
                "content": "疫情后，远程办公已成为许多企业的标配。如何在远程环境下保持高效协作，成为管理者面临的新挑战。",
                "sentiment_value": 0.1
            },
            {
                "title": "5G技术加速推进，产业链迎来新机遇",
                "content": "随着5G网络覆盖范围扩大，相关产业链企业迎来发展机遇。通信设备、芯片、应用软件等领域投资热度持续上升。",
                "sentiment_value": 0.9
            },
            {
                "title": "元宇宙概念热度不减，相关产业快速发展",
                "content": "元宇宙概念持续升温，游戏、社交、教育等领域积极布局。业内专家认为，元宇宙将成为互联网的下一个发展方向。",
                "sentiment_value": 0.5
            },
            {
                "title": "区块链技术在供应链管理中的应用",
                "content": "多家物流企业开始尝试将区块链技术应用于供应链管理，提高了透明度和效率，降低了成本和风险。",
                "sentiment_value": 0.6
            },
            {
                "title": "新能源汽车市场竞争加剧",
                "content": "随着传统车企加速电动化转型，新能源汽车市场竞争日趋白热化。消费者在产品丰富的同时，也面临选择困难。",
                "sentiment_value": 0.2
            },
            {
                "title": "碳中和目标下的能源转型",
                "content": "为实现碳中和目标，能源行业加速转型。太阳能、风能等可再生能源装机容量快速增长，传统能源企业面临转型压力。",
                "sentiment_value": 0.4
            },
            {
                "title": "教育改革措施落地，在线教育迎来新变革",
                "content": "近期，教育部发布多项改革措施，在线教育行业面临新的监管环境。行业洗牌加速，头部企业优势明显。",
                "sentiment_value": -0.1
            },
            {
                "title": "医疗健康产业创新加速",
                "content": "新技术在医疗健康领域的应用不断深入，远程医疗、AI辅助诊断等创新模式正在改变传统医疗服务方式。",
                "sentiment_value": 0.7
            },
            {
                "title": "电子商务平台新规实施后的市场反应",
                "content": "《电子商务平台管理办法》实施后，多家平台调整运营策略，平台责任边界更加清晰，市场竞争更加规范。",
                "sentiment_value": 0.3
            },
            {
                "title": "短视频平台用户增长放缓，行业进入存量竞争",
                "content": "短视频平台用户增长明显放缓，获客成本持续上升。平台间竞争从用户规模转向用户时长和商业化效率。",
                "sentiment_value": -0.2
            },
            {
                "title": "直播带货新规出台，行业洗牌加速",
                "content": "直播带货新规要求主播需持证上岗，对产品真实性负责。大量不合规主播退出市场，行业集中度提高。",
                "sentiment_value": -0.3
            },
            {
                "title": "智能家居市场规模持续扩大",
                "content": "随着物联网技术成熟和5G普及，智能家居进入快速发展期。家电、安防、照明等领域智能化程度不断提高。",
                "sentiment_value": 0.6
            },
            {
                "title": "物联网技术赋能传统产业数字化转型",
                "content": "物联网技术与传统产业深度融合，制造、农业、物流等行业数字化转型加速，运营效率显著提升。",
                "sentiment_value": 0.8
            },
            {
                "title": "大数据应用场景不断拓展",
                "content": "大数据技术从互联网向政务、金融、医疗等领域快速渗透，数据驱动决策已成为各行业的共识。",
                "sentiment_value": 0.5
            },
            {
                "title": "云计算服务需求激增，头部企业优势明显",
                "content": "疫情加速企业上云进程，云计算服务需求大幅增长。阿里云、腾讯云等头部企业市场份额进一步扩大。",
                "sentiment_value": 0.7
            },
            {
                "title": "国产芯片技术取得突破性进展",
                "content": "在国家政策支持下，多家芯片企业研发取得突破。14nm工艺实现量产，7nm工艺研发进展顺利。",
                "sentiment_value": 0.9
            },
            {
                "title": "数据泄露事件频发，企业信息安全建设亟待加强",
                "content": "近期多家企业遭遇数据泄露，用户信息被公开售卖。专家呼吁加强信息安全建设，完善数据保护机制。",
                "sentiment_value": -0.8
            },
            {
                "title": "社交平台监管趋严，行业生态面临调整",
                "content": "多部门联合发文，加强社交平台内容监管。平台审核标准提高，内容生态面临重构，创作者生存空间受到挤压。",
                "sentiment_value": -0.5
            },
            {
                "title": "共享经济遇冷，多家平台陷入亏损",
                "content": "共享单车、共享充电宝等共享经济模式遇冷，投资热度下降，多家平台持续亏损，商业模式可持续性受到质疑。",
                "sentiment_value": -0.7
            },
            {
                "title": "算法推荐被指加剧社会分化，专家呼吁加强监管",
                "content": "有研究表明，算法推荐可能强化用户认知偏差，加剧社会分化。专家呼吁平台增加算法透明度，加强算法伦理建设。",
                "sentiment_value": -0.4
            },
            {
                "title": "知识产权保护不力，内容创作者维权难",
                "content": "网络平台知识产权保护机制不完善，内容被盗用现象普遍，创作者维权成本高、周期长，权益难以得到有效保障。",
                "sentiment_value": -0.6
            }
        ]
        
        now = timezone.now()
        created_sentiments = []
        
        for data in sentiments_data:
            # 随机选择平台
            platform = random.choice(platforms)
            
            # 随机生成热度值 (100-10000)
            heat_value = random.randint(100, 10000)
            
            # 随机生成发布时间（过去7天内）
            days_ago = random.randint(0, 6)
            hours_ago = random.randint(0, 23)
            minutes_ago = random.randint(0, 59)
            publish_time = now - timedelta(days=days_ago, hours=hours_ago, minutes=minutes_ago)
            
            # 创建舆情数据
            sentiment = SentimentData.objects.create(
                title=data["title"],
                content=data["content"],
                url=f"https://example.com/news/{len(created_sentiments)+1}",
                platform=platform,
                sentiment_value=data["sentiment_value"],
                heat_value=heat_value,
                publish_time=publish_time
            )
            
            # 随机关联2-4个关键词
            num_keywords = random.randint(2, 4)
            selected_keywords = random.sample(keywords, min(num_keywords, len(keywords)))
            
            for keyword in selected_keywords:
                # 随机生成词频 (1-10)
                frequency = random.randint(1, 10)
                
                # 创建关联
                SentimentKeywordRelation.objects.create(
                    sentiment=sentiment,
                    keyword=keyword,
                    frequency=frequency
                )
            
            created_sentiments.append(sentiment)
        
        self.stdout.write(f'已添加 {len(created_sentiments)} 条舆情数据')
        return created_sentiments

    def add_alert_rules(self, targets):
        """添加预警规则"""
        # 清空现有数据
        AlertRule.objects.all().delete()
        
        # 预警规则类型
        condition_types = [
            "sentiment_negative",  # 负面情感
            "keyword_frequency",   # 关键词频率
            "heat_threshold",      # 热度阈值
            "sudden_increase"      # 突发增长
        ]
        
        created_rules = []
        
        # 为每个重点监控目标创建规则
        for target in targets:
            if not target.is_priority:
                continue
            
            # 为每种规则类型创建一条规则
            for condition_type in condition_types:
                # 根据规则类型设置阈值
                if condition_type == "sentiment_negative":
                    threshold = random.uniform(-1.0, -0.5)
                elif condition_type == "keyword_frequency":
                    threshold = random.randint(5, 20)
                elif condition_type == "heat_threshold":
                    threshold = random.randint(5000, 9000)
                else:  # sudden_increase
                    threshold = random.uniform(1.5, 3.0)
                
                # 设置时间窗口 (30分钟到24小时)
                time_window = random.choice([30, 60, 120, 240, 360, 720, 1440])
                
                rule = AlertRule.objects.create(
                    name=f"{target.name}-{condition_type}预警",
                    target=target,
                    condition_type=condition_type,
                    threshold=threshold,
                    time_window=time_window
                )
                
                created_rules.append(rule)
        
        self.stdout.write(f'已添加 {len(created_rules)} 条预警规则')
        return created_rules

    def add_alert_logs(self, rules, sentiments):
        """添加预警日志"""
        # 清空现有数据
        AlertLog.objects.all().delete()
        
        created_logs = []
        
        # 为部分规则创建预警日志
        sample_rules = random.sample(rules, min(len(rules) // 2, len(rules)))
        
        for rule in sample_rules:
            # 随机选择触发时间（过去3天内）
            days_ago = random.randint(0, 2)
            hours_ago = random.randint(0, 23)
            minutes_ago = random.randint(0, 59)
            triggered_at = timezone.now() - timedelta(days=days_ago, hours=hours_ago, minutes=minutes_ago)
            
            # 随机决定是否已处理
            is_handled = random.choice([True, False])
            
            # 如果已处理，设置处理时间
            handled_at = None
            if is_handled:
                # 处理时间在触发时间之后1小时内
                handling_delay = random.randint(5, 60)  # 5-60分钟
                handled_at = triggered_at + timedelta(minutes=handling_delay)
            
            # 设置触发值
            if rule.condition_type == "sentiment_negative":
                trigger_value = random.uniform(-1.0, rule.threshold)
            elif rule.condition_type == "keyword_frequency":
                trigger_value = random.randint(int(rule.threshold), int(rule.threshold) * 2)
            elif rule.condition_type == "heat_threshold":
                trigger_value = random.randint(int(rule.threshold), 15000)
            else:  # sudden_increase
                trigger_value = random.uniform(rule.threshold, rule.threshold * 1.5)
            
            log = AlertLog.objects.create(
                rule=rule,
                trigger_value=trigger_value,
                is_handled=is_handled,
                triggered_at=triggered_at,
                handled_at=handled_at
            )
            
            # 随机关联1-3条舆情数据
            sample_size = min(random.randint(1, 3), len(sentiments))
            related_sentiments = random.sample(sentiments, sample_size)
            for sentiment in related_sentiments:
                log.sentiments.add(sentiment)
            
            created_logs.append(log)
        
        self.stdout.write(f'已添加 {len(created_logs)} 条预警日志')
        return created_logs

    def add_system_status(self):
        """添加系统状态"""
        # 清空现有数据
        SystemStatus.objects.all().delete()
        
        services = [
            {"name": "舆情爬虫", "type": "crawler", "status": True, "response_time": random.randint(50, 200)},
            {"name": "情感分析", "type": "nlp", "status": True, "response_time": random.randint(100, 300)},
            {"name": "API服务", "type": "api", "status": True, "response_time": random.randint(20, 100)},
            {"name": "数据库服务", "type": "database", "status": True, "response_time": random.randint(10, 50)},
            {"name": "缓存服务", "type": "cache", "status": True, "response_time": random.randint(5, 30)}
        ]
        
        created_services = []
        
        for service in services:
            status = SystemStatus.objects.create(
                name=service["name"],
                type=service["type"],
                status=service["status"],
                response_time=service["response_time"]
            )
            created_services.append(status)
        
        self.stdout.write(f'已添加 {len(created_services)} 条系统状态记录')
        return created_services

    def add_daily_statistics(self):
        """添加每日统计数据"""
        # 清空现有数据
        DailyStatistics.objects.all().delete()
        
        created_stats = []
        
        # 生成过去30天的数据
        today = timezone.now().date()
        
        for days_ago in range(30):
            date = today - timedelta(days=days_ago)
            
            # 生成随机数据
            total = random.randint(1000, 5000)
            positive = random.randint(int(total * 0.2), int(total * 0.4))
            negative = random.randint(int(total * 0.1), int(total * 0.3))
            neutral = total - positive - negative
            alert_count = random.randint(5, 20)
            
            stats = DailyStatistics.objects.create(
                date=date,
                total_count=total,
                positive_count=positive,
                neutral_count=neutral,
                negative_count=negative,
                alert_count=alert_count
            )
            
            created_stats.append(stats)
        
        self.stdout.write(f'已添加 {len(created_stats)} 条每日统计数据')
        return created_stats 